/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.DoctorLettersDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;
import lu.med.praxiswahl.wahlumed.model.beans.DoctorLettersTBL;

/**
*
* @author Patrick kendzo
* Email: pkendzo@msn.com
*/

@Stateless
public class DoctorLettersDAO implements DoctorLettersDAOInt
{

	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager	em;

	public DoctorLettersDAO()
	{

	}

	@Override
	public void delete(Long id)
	{
		DoctorLettersTBL docLetter = em.find(DoctorLettersTBL.class, id);

		CustomerTBL cust = docLetter.getCustomer();

		cust.getDocLetter().remove(docLetter);

		em.remove(docLetter);
		em.flush();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DoctorLettersTBL> findDocLetterByCustomer(String matricule)
	{
		try
		{

			List<DoctorLettersTBL> resultList = (List<DoctorLettersTBL>) em
					.createQuery(
							"select d from DoctorLettersTBL d where d.customer = '"
									+ matricule + "' order by d.datum desc").getResultList();
			return resultList;
		}
		catch (Exception e)
		{
			throw new RuntimeException("Ordonance for this typ can be found ",
					e);
		}
	}

	@Override
	public Long findDatabaseSubPrimaryKeyIndex()
	{
		try
		{
			
			Long result = (Long)em
					.createQuery(
							"select max(artzbriefen_nummer) from DoctorLettersTBL d ").getSingleResult();
			
			return result.longValue();
		}
		catch (Exception e)
		{
			/*throw new RuntimeException("OrdonanceTBL is empty",
					e);*/
			return -1l;
		}
	}

	@Override
	public void persist(DoctorLettersTBL todo)
	{
		em.persist(todo);
		em.flush();

	}

	@Override
	public DoctorLettersTBL retrieveDoctorLetterByID(Long id)
	{
		return (DoctorLettersTBL) em.find(DoctorLettersTBL.class, id);
	}

	@Override
	public void update(DoctorLettersTBL todo)
	{
		em.merge(todo);
		em.flush();

	}

}
